Skip to content


tag  jupyter  tips  ai  deep learning  beginner  regression  ardupilot  None  ros2  dds  micro ros  xrce  sitl  plugin  SITL  debug  rangefinder  pymavlink  mavros  gazebo  distance sensor  system_time  timesync  cmake  gtest  ctest  101  cpp  c++  format  fmt  multithreading  spdlog  cyclonedds  eprosima  fastdds  simulation  config  ignition  bridge  sdf  ign-transport  camera  sensors  lidar  aptly  apt  repository  repo  local  mirror  encryption  pgp  docker  compose  tutorial  networking  network  nvidia  python  app  devcontainer  gui  multi-stage  stage  git  bundle  submodules  github  hooks  pre-commit  lxd  container  lxc  x11  profile  vscode  marpit  presentation  marp  markdown  mermaid  mkdocs  video  ffmpeg  gstreamer  cheat-sheet  sdp  v4l2loopback  gi  kml  geo  gis  spatial  gdal  ogr  raster  vector  snippets  cheat Sheet  asyncio  future  click  cli  deb  debian  package  setup  stdeb  project  numpy  template  black  isort  templates  cookiecutter  docs  project document  docstrings  flake8  linter  git-hook  mypy  unittest  pytest  pylint  from a-z  mock  iterator  generator  yaml  yml  logging  tuple  namedtuple  typing  annotation  typever  pyzmq  zmq  msgpack  action  namespace  remap  control2  ros2_control  effort  velocity  gdb  qos  plugins  msg  node  zero-copy  shm  algorithm  calibration  diff  pid  dev  colcon  colcon_cd  settings  behavior  py_trees  bt  behavior_trees  blackboard  plot  visualization  debugging  diagnostic  DiagnosticTask  diagnostics  tutorials  gst  math  apm  rat_runtime_monitor  web  rosbridge  vue  binding  discovery  gazebo-classic  launch  spawn  model  cook  gps  imu  ray  gazebo_ros_ray_sensor  ultrsonic  range  ultrasonic  gazebo classic  wrench  odom  ign  gz  xacro  ros_ign  diff_drive  odometry  joint_state  argument  OpaqueFunction  DeclareLaunchArgument  LaunchConfiguration  tmux  nav  slam  test  rclpy  goal abort  cancel goal  action client  action server  custom messages  executor  MultiThreadedExecutor  SingleThreadedExecutor  param  dynamic-reconfigure  service  client  setup.py  package.xml  parameter  parameters  custom  msgs  executers  pub  sub  rqt  rviz  rviz2  pose  marker  tf2  local_setup  rosdep  package manager  project settings  vcstool  urdf  robot_state_publisher  urdf_to_graphiz  joint  link  zenoh  cross-compiler  nano  rpi  texture  joints  tmuxp  loop device  rootfs  embedded  zah  linux  rm  ubuntu  sudo  sudoers  nopasswd  visudo  udev  key  gpg  sign  ip  ss  netstat  snap  deploy  ssh  systemd  socat  serial  udp  tc  mtu  select  robotics  kalman_filter  kalman  filter  control  code  extensions  json  schema  dev container  yocto  poky  qemu  projects  courses to follow  world  gazebo_ros2_control  position_controller  effort_controller  velocity_controller  gazebo_ros_force  gazebo_ros_joint_state_publisher  joint_state_publisher  vrx  buoyancy 

Minimal Pub/Sub with namespace and remapping topics


LAB#

  • Create minimal Pub/Sub with different topic
  • remapping topic from command line
  • remapping from launch
  • add namespace
  • change node name

Minimal nodes#

minimal_pub.py
import rclpy
from rclpy.node import Node
from std_msgs.msg import String

TOPIC = "simple"
PERIOD = 1

class MyNode(Node):
    def __init__(self):
        node_name="minimal_pub"
        super().__init__(node_name)
        self.__pub = self.create_publisher(String, TOPIC, 10)
        self.__timer = self.create_timer(PERIOD, self.__timer_handler)
        self.__timer
        self.__counter = 0
        self.get_logger().info("run simple pub")

    def __timer_handler(self):
        self.__counter += 1
        msg = String(data="pub counter: {}".format(self.__counter))
        self.__pub.publish(msg)

def main(args=None):
    rclpy.init(args=args)
    node = MyNode()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()
minimal_sub.py
import rclpy
from rclpy.node import Node
from std_msgs.msg import String

TOPIC = "simple1"

class MyNode(Node):
    def __init__(self):
        node_name="minimal_sub"
        super().__init__(node_name)
        self.__sub = self.create_subscription(String, TOPIC, self.__sub_handler, 10)
        self.__sub
        self.get_logger().info("start minimal sub")

    def __sub_handler(self, msg: String):
        self.get_logger().info(msg.data)

def main(args=None):
    rclpy.init(args=args)
    node = MyNode()
    rclpy.spin(node)
    node.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()
setup.py
# Add entry points
entry_points={
        'console_scripts': [
            "minimal_pub=py_tutorial_pkg.minimal_pub:main",
            "minimal_sub=py_tutorial_pkg.minimal_sub:main"
        ],
    }

first run#

terminal1
ros2 run py_tutorial_pkg minimal_pub
terminal2
ros2 run py_tutorial_pkg minimal_sub
terminal3
# nodes
ros2 node list
/minimal_pub
/minimal_sub

# topics
ros2 topic list
/parameter_events
/rosout
/simple
/simple1

# info topic /simple
ros2 topic info /simple
Type: std_msgs/msg/String
Publisher count: 1
Subscription count: 0

# info topic /simple1
ros2 topic info /simple1
Type: std_msgs/msg/String
Publisher count: 0
Subscription count: 1

usage remapping sub topic#

terminal2
ros2 run py_tutorial_pkg minimal_sub --ros-args -r simple1:=simple
terminal3
ros2 topic list
/parameter_events
/rosout
/simple

launch with remapping#

run_minimal_1.launch.py
from launch import LaunchDescription
from launch_ros.actions import Node

def generate_launch_description():
    ld = LaunchDescription()

    pub_node =  Node(
            package='py_tutorial_pkg',
            executable='minimal_pub'
        )

    sub_node =  Node(
            package='py_tutorial_pkg',
            executable='minimal_sub',
            remappings=[
                ('/simple1', '/simple'),
            ]
        )

    ld.add_action(pub_node)
    ld.add_action(sub_node)
    return ld
terminal1
ros2 launch py_tutorial_pkg run_minimal1.launch.py
terminal2
# nodes
ros2 node list
/minimal_pub
/minimal_sub

# topics
ros2 topic list
/parameter_events
/rosout
/simple

Add namespace#

terminal1
ros2 run py_tutorial_pkg minimal_pub --ros-args -r __ns:=/demo
terminal2
ros2 run py_tutorial_pkg minimal_sub --ros-args -r __ns:=/other_demo
terminal3
# nodes
ros2 node list
/demo/minimal_pub
/other_demo/minimal_sub

# topics
ros2 topic list
/demo/simple
/other_demo/simple1

remap pub this time#

terminal1
ros2 run py_tutorial_pkg minimal_pub --ros-args -r __ns:=/demo -r /demo/simple:=/other_demo/simple1
terminal3
# nodes
ros2 topic list
/demo/other_demo/simple1
/other_demo/simple1

# topics
ros2 topic list
/other_demo/simple1

with launch file#

  • Add namespace
  • Remap topic with full namespace
run_minimal_2.launch.py
from launch import LaunchDescription
from launch_ros.actions import Node

def generate_launch_description():
    ld = LaunchDescription()

    pub_node =  Node(
            package='py_tutorial_pkg',
            executable='minimal_pub',
            namespace="/demo",
            remappings=[
                ('/demo/simple', '/other_demo/simple1'),
            ]
        )

    sub_node =  Node(
            package='py_tutorial_pkg',
            executable='minimal_sub',
            namespace="/other_demo"

        )

    ld.add_action(pub_node)
    ld.add_action(sub_node)
    return ld